import * as fs from 'fs';
import * as Koa from 'koa';
import * as jwt from 'koa-jwt';

import env from './config/env';

const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser')();
const logger = require('koa-logger');

const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const convert = require('koa-convert');
const serve = require('koa-static');
let log4js = require('koa-log4');
import log4jsConfig from './config/log4j.json';
onerror(app);

let appenders: any[] = log4jsConfig.appenders;
//
if (!fs.existsSync(env.logPath)) {
    fs.mkdirSync(env.logPath);
}
appenders.forEach(value => {
    let filename: string = value.filename;

    let path: string = '';
    if (filename) {
        path = filename.substring(0, filename.lastIndexOf("/"));
    }
    if (value.filename && !fs.existsSync(path)) {

        fs.mkdirSync(path);
    }
});

log4js.configure(log4jsConfig);
app.use(log4js.koaLogger(log4js.getLogger("access"), { level: 'auto' }));
// middlewares
app.use(bodyparser);
app.use(json());
app.use(require('koa-static')(__dirname + '/public'));
//public/images/xxxxxx
app.use(views(__dirname + '/views', {
  // extension: 'pug'
  map: {
    html: 'handlebar'
  }
}));
// logger

app.use(logger());
app.use(bodyParser());
app.keys = ['some secret hurr'];
app.use(convert(session(app)));
app.use(serve(__dirname + '/public'));

//安全校验
app.use(jwt({ secret: env.secret, passthrough: false }).unless({
  path: [
    /^\/api\/motor\/*/
  ]
}));

//dingConfig.init(app, env as any, [/^\/api\/auth\/*/])

//加载路由
let routers_path = __dirname + '/routes/';
let routers = fs.readdirSync(routers_path);
let list: any[] = [];
routers.forEach(element => {
  let stat = fs.lstatSync(routers_path + element);
  if (!stat.isDirectory()) {
    list.push(element);
  }
});
list.map(file => {
  let mpath = "./routes/";
  let route = require(mpath + file.substring(0, file.lastIndexOf('.')));
  app.use(route.default.routes())
})

export default app;
